//
//  MapNode.m
//  CompGraf2
//
//  Created by Juan Niosi on 29/09/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MapNode.h"
#import "World.h"

@implementation MapNode
@synthesize x,y,parent,g,h,worldPos;
- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (id)initWithCoords:(int)cx :(int)cy
{
    self = [super init];
    if (self) {
        self.x = cx;
        self.y = cy;
        self.parent = NULL;
        [self calcG];
        self.h = 0;
        
        [self setWorldPos:[[World getWorld].terrain mapNode2vert:self]]; 
    }
    
    return self;
}

- (id)initWithCoords:(int)cx :(int)cy setParent:(MapNode *)prnt
{
    self = [super init];
    if (self) {
        self.x = cx;
        self.y = cy;
        self.parent = prnt;
        [self calcG];
        self.h = 0;
    }
    
    return self;
}

- (BOOL)equals:(MapNode *)node
{
    return  (self.x == [node x] && self.y == [node y]);
}

- (BOOL)equals:(int)cx :(int)cy
{
    return (self.x == cx && self.y == cy);
}

- (void)calcG
{
    if (self.parent == nil)
    {
        g = 0;
    }
    else
    {
        g = self.parent.g;
        if (abs(self.x - self.parent.x) + abs(self.y - self.parent.y) == 2)
        {
            //Diagonal
            g += 1.40f;
        }
        else
        {
            //Recto
            g += 1.00f;
        }
    }    
}

- (void)calcH:(MapNode *)final
{
    float distX = final.x - self.x;
    float distY = final.y - self.y;
    h = sqrtf(distX*distX + distY*distY);
}

- (float)getF
{
    return g+h;
}
               
- (void)updateParent:(MapNode *)prnt
{
    self.parent = prnt;
    [self calcG];
}

- (NSArray *)getHierarchy
{
    NSMutableArray *hierarchy = [[NSMutableArray alloc] init];
    MapNode *current = self;
    while (current)
    {
        [hierarchy insertObject:current atIndex:0];
        current = current.parent;
    }
    return [[NSArray alloc] initWithArray:hierarchy];
}

- (void)dealloc
{
    [parent release];
    [worldPos release];
    
    [super dealloc];
}
@end
